package server.orders;

import java.io.IOException;
import java.sql.Date;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import json.JSONObjectWrapper;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import server.database.AbstractTable;
import server.database.DatabaseService;
import server.database.query.IQueryResult;
import server.servlet.AbstractServlet;
import utils.DateUtils;
import utils.StringUtils;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

public class OrdersDashboardServlet extends AbstractServlet
{
	private static final long serialVersionUID = 872775197875032811L;

	public static final String PATH = API + "/orders_dashboard";

	public static final String MONTH = "month";
	public static final String SALES = "sales";
	public static final String SALE_NUMBERS = "sale_numbers";

	public static final String SALES_LABEL = "Sales";

	public static final String X_AXIS_KEY = "xkey";
	public static final String Y_AXIS_KEY = "ykeys";
	public static final String LABELS = "labels";
	public static final String DATA = "data";

	public static final String ORDERS_DASHBOARD = "orders_dashboard";

	@Override
	protected void doGetSpecific(HttpServletRequest request, HttpServletResponse response, JSONObject output) throws ServletException, IOException
	{
		IQueryResult queryResult = null;

		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.DAY_OF_MONTH, 1);
		calendar.add(Calendar.MONTH, -2);

		Date queryDate = new Date(calendar.getTimeInMillis());

		String sWhereString = " WHERE " + OrdersTable.OPEN_DATE.getName() + " >= " + AbstractTable.parseDateForQuery(queryDate);

		String sSalesmanID = request.getParameter(getTable().SALESMAN_ID.getName());
		if (!StringUtils.isEmpty_DB(sSalesmanID))
		{
			sWhereString += AbstractTable.AND + OrdersTable.SALESMAN_ID.getName() + "=" + sSalesmanID;
		}

		queryResult = getTable().getAllEntities(sWhereString);

		if (queryResult.getResult() == IQueryResult.SUCESS)
		{
			output.put(RESULT, true);

			JSONObject orders_dashboard = new JSONObject();
			buildSalesData(queryResult.getResultValues(), orders_dashboard);
			output.put(ORDERS_DASHBOARD, orders_dashboard);

		}
		else if (queryResult.getResult() != IQueryResult.NO_RESULTS)
		{
			setFail(output, UNEXPECTED_ERROR, UNEXPECTED_ERROR);
		}
		else
		{
			output.put(RESULT, false);
			output.put(QUERY_RESULT, IQueryResult.NO_RESULTS);
		}

	}

	private void buildSalesData(List<Map<String, String>> resultValues, JSONObject orders_dashboard)
	{
		List<Map<String, Object>> lstMonths = Lists.newArrayList();

		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.DAY_OF_MONTH, 1);
		calendar.add(Calendar.MONTH, -2);

		for (int i = 0; i <= 2; i++)
		{
			Map<String, Object> monthMap = Maps.newHashMap();
			monthMap.put(SALES, 0);
			monthMap.put(SALE_NUMBERS, 0);
			monthMap.put(MONTH, DateUtils.getSQLDateMonth(calendar.get(Calendar.MONTH)));
			lstMonths.add(monthMap);

			calendar.add(Calendar.MONTH, 1);
		}

		for (Map<String, String> order : resultValues)
		{
			String sMonth = DateUtils.getSQLDateMonth(order.get(OrdersTable.OPEN_DATE.getName()));

			Map<String, Object> orderMonth = lstMonths.get(getMonthIndex(lstMonths, sMonth));

			int iSales = (Integer) orderMonth.get(SALE_NUMBERS) + 1;
			orderMonth.put(SALE_NUMBERS, iSales);

			// TODO - implement for $$$

			// months.put(sMonth, orderMonth);
		}

		JSONArray saleNumbersData = new JSONArray();
		JSONArray sales = new JSONArray();
		for (Map<String, Object> monthMap : lstMonths)
		{
			JSONObject monthSaleNumbers = new JSONObject();
			monthSaleNumbers.put(MONTH, monthMap.get(MONTH));
			monthSaleNumbers.put(SALE_NUMBERS, monthMap.get(SALE_NUMBERS));
			saleNumbersData.add(monthSaleNumbers);
		}

		parseSaleNumbersData(saleNumbersData, orders_dashboard);

	}
	private void parseSaleNumbersData(JSONArray saleNumbersData, JSONObject orders_dashboard)
	{
		JSONObject saleNumbers = new JSONObject();
		saleNumbers.put(X_AXIS_KEY, MONTH);

		JSONArray saleNumbesYKey = new JSONArray();
		saleNumbesYKey.add(SALE_NUMBERS);
		saleNumbers.put(Y_AXIS_KEY, saleNumbesYKey);

		JSONArray salesLabelArray = new JSONArray();
		salesLabelArray.add(SALES_LABEL);
		saleNumbers.put(LABELS, salesLabelArray);
		saleNumbers.put(DATA, saleNumbersData);

		orders_dashboard.put(SALE_NUMBERS, saleNumbers);
	}

	private int getMonthIndex(List<Map<String, Object>> lstMonts, String sMonth)
	{
		for (Map<String, Object> month : lstMonts)
		{
			if (month.get(MONTH).equals(sMonth))
			{
				return lstMonts.indexOf(month);
			}
		}

		return -1;
	}

	@Override
	protected void doPostSpecific(JSONObjectWrapper request, JSONObject output) throws ServletException, IOException
	{
	}

	@Override
	protected OrdersTable getTable()
	{
		return (OrdersTable) DatabaseService.getInstance().getTable(OrdersTable.TABLE_NAME);
	}

}
